package com.imooc.ecommerce.conf;

import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * Seata所需要的数据源代理配置类
 * @author zhangshao
 * @since 2023/12/14 21:14
 */
@Configuration
public class DataSourceProxyAutoConfiguration {

    @Autowired
    private DataSourceProperties dataSourceProperties;

    /**
     * 配置数据源代理用于Seata全局事务回滚
     * before image + after image --> undo.log
     * @return
     */
    @Primary
    @Bean("dataSource")
    public DataSource dataSource(){
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(dataSourceProperties.getUrl());
        dataSource.setUsername(dataSourceProperties.getUsername());
        dataSource.setPassword(dataSourceProperties.getPassword());
        dataSource.setDriverClassName(dataSourceProperties.getDriverClassName());

        return new DataSourceProxy(dataSource);
    }
}
